package com.ym.livedemo

import android.Manifest
import android.os.Build
import android.os.Bundle
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.ym.livedemo.api.BusinessViewModel
import com.ym.livedemo.databinding.ActivityMainBinding
import com.ym.livedemo.live.AudienceActivity
import com.ym.livedemo.live.CreateLiveActivity
import com.ym.livedemo.live1.AnchorSettingsActivity
import com.ym.livedemo.utils.SPUtils
import splitties.activities.start

class MainActivity : AppCompatActivity() {
    private var permissionsRequestCode = 2022
    private var isAgreePermission = true
    private val viewModel by viewModels<BusinessViewModel>()

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val viewBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)
        SystemBarHelper.immersiveStatusBar(this, 0f)
        init()

        viewBinding.anchor.setOnClickListener {
            if (isAgreePermission) {
                start<CreateLiveActivity>()
            } else {
                requestPermission()
            }
        }
        viewBinding.liveSettings.setOnClickListener {
            if (isAgreePermission) {
                start<AnchorSettingsActivity>()
            } else {
                requestPermission()
            }
        }
        viewBinding.audience.setOnClickListener {
            start<AudienceActivity>()
        }
        requestPermission()
    }

    private fun init() {
        Constant.UID = SPUtils.get(this, Constant.UID_KEY, 321) as Int
        Constant.TOKEN = SPUtils.get(this, Constant.TOKEN_KEY, "") as String
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun requestPermission() {
        requestPermissions(
            arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), permissionsRequestCode
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == permissionsRequestCode) {
            isAgreePermission = true
            grantResults.forEach {
                if (it == -1) {
                    isAgreePermission = false
                    return@forEach
                }
            }
        }
    }
}